package com.titaniume.tx;

import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

/**
 * @program: redis-study
 * @description: Redis 测试事务
 * @author: titaniume
 * @create: 2022-01-13 10:59
 */
public class TestTX {
    public static void main(String[] args) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.flushDB();


        JSONObject jsonObject = new JSONObject();
        jsonObject.put("hello","woreld");
        jsonObject.put("name","redis");
        //开启事务
        Transaction multi = jedis.multi();
        try {
            String result = jsonObject.toJSONString();
            multi.set("user1",result);
            multi.set("user2",result);
            int i  = 10 / 0; //代码抛出异常，执行失败
            //执行事务
            multi.exec();
        } catch (Exception e) {
            multi.discard(); //放弃事务
            e.printStackTrace();
        }finally {
            System.out.println(jedis.get("user1"));
            System.out.println(jedis.get("user2"));
            jedis.close(); //关闭连接
        }
    }
}